package com.jiajunsong.blog.controller;

import java.io.IOException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.jiajunsong.blog.config.BlogProperty;
import com.jiajunsong.blog.domain.Authority;
import com.jiajunsong.blog.domain.Blog;
import com.jiajunsong.blog.domain.Catalog;
import com.jiajunsong.blog.domain.Comment;
import com.jiajunsong.blog.domain.Result;
import com.jiajunsong.blog.domain.User;
import com.jiajunsong.blog.repository.AuthorityRepository;
import com.jiajunsong.blog.repository.BlogRepository;
import com.jiajunsong.blog.repository.CatalogRepository;
import com.jiajunsong.blog.repository.CommentRepository;
import com.jiajunsong.blog.repository.UserRepository;

@RestController
public class MainController {
	@Autowired
	private BlogRepository blogRepository;
	@Autowired
	private UserRepository userRepository;
	@Autowired
	private CommentRepository commentRepository;
	@Autowired
	private CatalogRepository catalogRepository;
	@Autowired
	private AuthorityRepository authorityRepository;
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private BlogProperty blogProperty;

	@Value("${server.port}")
	private Long serverPort;

	private Logger logger = LoggerFactory.getLogger(getClass());

	/*
	 * @GetMapping("/login") public ModelAndView login() { return new
	 * ModelAndView("login"); }
	 */

	/*
	 * @GetMapping("/login") public Result login() { List<String> list = new
	 * ArrayList<String>(); list.add("list1"); list.add("list2"); list.add("list3");
	 * return new Result("",list); }
	 */

	@GetMapping("/login")
	public Result login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		RequestCache requestCache = new HttpSessionRequestCache();
		RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

		SavedRequest savedRequest = requestCache.getRequest(request, response);

		if (savedRequest != null) {
			String targetUrl = savedRequest.getRedirectUrl();
			logger.info("引发跳转的请求是:" + targetUrl);
			if (StringUtils.endsWithIgnoreCase(targetUrl, ".html")) {
				redirectStrategy.sendRedirect(request, response, "/login.html");
			}
		}
		return new Result("请登录");
	}
	@GetMapping("/login.html")
	public ModelAndView longinhtml() {
		return new ModelAndView("/login.html");
	}
	@GetMapping("/hello.html")
	public ModelAndView hellohtml() {
		return new ModelAndView("/hello.html");
	}
	@GetMapping("/hello")
	public Result hello(HttpServletRequest request) {

		logger.info("RequestURI:"+request.getRequestURI());
		return new Result("/hello：" + blogProperty.getDesingedBy() + (serverPort + 1));
	}
	
	@GetMapping("/hello2")
	public Result hello2(HttpServletRequest request) {
		List<String> list = new ArrayList<String>();
		list.add("hello");
		list.add("world");
		System.out.println(list.get(0));
		System.out.println(list.iterator().next());
		logger.info("RequestURI:"+request.getRequestURI());
		return new Result("/hello2：" + blogProperty.getDesingedBy() + serverPort);
	}

	@GetMapping("/me")
	public Result me(Authentication authentication) {
		
		if (authentication == null) {
			return new Result("未登录");
		} else {
			return new Result("", authentication);
		}
	}

	@GetMapping("/me2")
	public Result me2(@AuthenticationPrincipal UserDetails userDetails) {
		if (userDetails == null) {
			return new Result("未登录");
		} else {
			return new Result("", userDetails);
		}
	}

	@GetMapping("/init")
	public void init() {
		List<Authority> authorities = new ArrayList<>();
		Authority admin = new Authority();
		admin.setAuthority("ROLE_ADMIN");
		authorityRepository.save(admin);
		Authority user = new Authority();
		user.setAuthority("ROLE_USER");
		authorityRepository.save(user);
		authorities.add(user);
		authorities.add(admin);

		User user1 = new User("admin", "管理员", passwordEncoder.encode("123456"), "admin@jiajunsong.com");
		user1.setAuthorities(authorities);
		userRepository.save(user1);

		User user2 = new User("user", "贾俊松", passwordEncoder.encode("123456"), "jjsjjs521@163.com");
		List<Authority> authorities2 = new ArrayList<>();
		authorities2.add(user);
		user2.setAuthorities(authorities2);
		userRepository.save(user2);

		Catalog catalog1 = new Catalog();
		catalog1.setName("java");
		catalog1.setUser(user1);
		catalogRepository.save(catalog1);

		Catalog catalog2 = new Catalog();
		catalog2.setName("C#");
		catalog2.setUser(user1);
		catalogRepository.save(catalog2);

		Catalog catalog3 = new Catalog();
		catalog3.setName("java");
		catalog3.setUser(user2);
		catalogRepository.save(catalog3);

		Catalog catalog4 = new Catalog();
		catalog4.setName("C#");
		catalog4.setUser(user2);
		catalogRepository.save(catalog4);

		for (int i = 1; i <= 40; i++) {
			Blog blog = new Blog();
			blog.setCatalog(catalog3);
			blog.setUser(user2);
			blog.setTitle("title" + i);
			blog.setHtmlContent("<h3>content" + i + "</h3>");
			blog.setReadSize(i);
			blog.setSummary("summary" + i);
			for (int j = 1; j < 5; j++) {
				Comment comment = new Comment();
				comment.setContent("comment" + j);
				comment.setUser(user1);
				// commentRepository.save(comment);//因为设置里级联保存，这里就可以不写，保存blog的时候会自动保存comment
				blog.addComment(comment);
			}
			blogRepository.save(blog);

		}

	}
	@GetMapping("/")
	public void index(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.sendRedirect("/index.html");
	}

}
